<!--
 * @Author: jingjingzheng 1742420988@qq.com
 * @Date: 2024-07-12 22:08:49
 * @LastEditors: zhengjingjing 1742420988@qq.com
 * @LastEditTime: 2025-02-12 17:18:05
 * @FilePath: \greencityldzbruoyi-ui\src\views\datamanage\citylvdao\dataPanel.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!--
 * @Author: jingjingzheng 1742420988@qq.com
 * @Date: 2024-07-12 22:08:49
 * @LastEditors: jingjingzheng 1742420988@qq.com
 * @LastEditTime: 2024-07-12 22:39:24
 * @FilePath: \greencity-ui\src\views\datamanage\citylvdao\dataPanel.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <!-- 城市绿道管理 -->
    <el-row>
      <el-col :span="24" class="title-row">
        <span>| 城市绿道确认</span>
      </el-col>
    </el-row>
    <div v-show="true">
      <div style="display: flex; justify-content: space-between">
        <el-switch
          v-model="showSearch"
          style="height: 33px"
          active-text="查询条件"
          active-color="#13ce66"
          @change="switchChange"
        ></el-switch>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              :disabled="multiple"
              v-hasPermi="['datamange:citylvdao:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope.row)"
              :disabled="multiple"
              v-hasPermi="['datamange:citylvdao:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5" v-show="true">
            <el-button
              type="primary"
              plain
              icon="el-icon-download"
              size="mini"
              :disabled="multiple"
              @click="handleExport()"
              v-hasPermi="['datamanage:citylvdao:export']"
              >导出</el-button
            >
          </el-col>
        </el-row>
      </div>
      <!-- 展开查询条件选择框 -->
      <el-form
        ref="form"
        :model="queryParams"
        label-width="80px"
        size="small"
        :inline="true"
        v-show="showSearch"
        class="queryPanel"
      >
        <el-form-item label="名称">
          <el-input v-model="queryParams.name" style="width: 10vw"></el-input>
        </el-form-item>
        <el-form-item label="行政区划" v-show="false">
          <el-cascader
            v-model="selectXzqhs"
            :options="xzqhOptions"
            :props="{ checkStrictly: true }"
            clearable
            @change="handleChangeXzqh"
            style="width: 10vw"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="核查状态">
          <el-select
            v-model="queryParams.hczt"
            placeholder="请选择"
            clearable
            style="width: 10vw"
            @change="handleChangeHczt"
          >
            <el-option
              v-for="dict in dict.type.greenregion_data_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="空间范围" size="normal">
          <el-button type="info" size="mini" @click="drawExtent('rectangle')"
            >矩形</el-button
          >
          <el-button type="info" size="mini" @click="drawExtent('polygon')"
            >多边形</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="20" style="text-align: center" v-show="showSearch">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-row>
    </div>

    <!-- 显示查询结果表单 -->
    <el-table
      :data="features"
      v-loading="loading"
      stripes
      higlight-current-row
      :height="tableHeight"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="编号"
        align="center"
        prop="attributes.objectid"
        width="50"
      />
      <el-table-column
        label="名称"
        width="150"
        align="center"
        :show-overflow-tooltip="true"
        prop="attributes.name"
      ></el-table-column>
      <el-table-column
        label="绿道宽度(m)"
        width="100"
        align="center"
        :show-overflow-tooltip="true"
        prop="attributes.swidth"
      ></el-table-column>
      <el-table-column
        label="绿道长度(m)"
        width="100"
        align="center"
        :show-overflow-tooltip="true"
        prop="attributes.slen"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.attributes.slen">
            {{ scope.row.attributes.slen.toFixed(2) }}
          </div>
          <div v-if="!scope.row.attributes.slen">
            {{ scope.row.attributes.slen }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="核查状态"
        width="100"
        align="center"
        :show-overflow-tooltip="true"
        prop="attributes.hczt"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.greenregion_data_status"
            :value="scope.row.attributes.hczt"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row, scope.index)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-location-outline"
            @click="handleLocate(scope.row, scope.index)"
            >定位</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      layout="total, sizes,prev, pager, next"
      @pagination="getList"
    />
  </div>
</template>

<script>
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import Graphic from "@arcgis/core/Graphic";
import SketchViewModel from "@arcgis/core/widgets/Sketch/SketchViewModel";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import { mapActions, mapGetters } from "vuex";
import { createLayer } from "../../../utils/map";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer";

export default {
  props: {
    mapview: { default: () => {} },
  },
  dicts: ["greenregion_data_status"],
  inject: ["toggleComponent"],
  data() {
    return {
      paramObj: {},
      split1: 0.6,
      // 显示搜索条件
      showSearch: false,
      tableHeight: "72vh",
      // 当前页要素集合
      features: [],
      // 要素图层title
      featureLayerTitle:
        window.mapConfig.operationLayers.mapservers["citylvdaolayer"].title,
      // 要素图层url
      featureLayerUrl:
        window.mapConfig.operationLayers.mapservers["citylvdaolayer"].url,
      //定位级别
      zoomLevel:
        window.mapConfig.operationLayers.mapservers["citylvdaolayer"].zoomLevel,
      // 概略查询字段
      outFields:
        window.mapConfig.operationLayers.mapservers["citylvdaolayer"].outFields,
      // 空间查询选中符号
      selectSymbol:
        window.mapConfig.operationLayers.mapservers["citylvdaolayer"].symbol,
      // 定位符号
      locateSymbol:
        window.mapConfig.operationLayers.mapservers["citylvdaolayer"].symbol,
      // 框选范围的符号
      selectExtentSymbol: window.mapConfig.symbols.selectExtent,
      // 遮罩层
      loading: false,
      // 选中的要素
      selectFeatures: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 查询范围
      queryExtent: null,
      // 属性查询条件
      whereClause: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: undefined,
        category_type: undefined,
        medium_type: undefined,
        suosjd: undefined,
        suossq: undefined,
        hczt: undefined,
        geometry: null,
      },
      // 查询数据总条数
      total: 0,
      // 行政区划下拉列表绑定选项
      xzqhOptions: [],
      // 行政区划选中值
      selectXzqhs: [],
      homeViewpoint: undefined,
    };
  },
  created() {
    let _self = this;
    _self.xzqhOptions = city;
  },
  activated() {
    if (this.featureLayer == undefined) {
      this.initFeatureLayer();
      return;
    }
    this.getList();
  },
  computed: { ...mapGetters(["dataScope"]) },
  methods: {
    ...mapActions("map", ["setHighlight", "removeHighlight", "cleanHighlight"]),
    /**
     * @description: 切换查询面板显示隐藏
     * @param {*}
     * @return {*}
     */
    switchChange(val) {
      console.log(val);
      if (val) {
        this.tableHeight = "60vh";
      } else this.tableHeight = "75vh";
      console.log("this is tableHeight");
      console.log(this.tableHeight);
    },
    // 查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /**
     * @description: 新增按钮
     * @param {*}
     * @return {*}
     */
    handleAdd() {
      let _self = this;
      let paramObj = {
        featureLayer: this.featureLayer,
      };
      this.toggleComponent("addPanel", paramObj);
    },
    /**
     * @description: 删除按钮
     * @param {*} row 数据行
     * @return {*}
     */
    handleDelete(row) {
      let _self = this;
    },

    /**
     * @description: 导出数据
     * @param {*} row 数据行
     * @return {*}
     */
    handleExport(row) {},
    /**
     * @description: 多选框选中数据
     * @param {*} selection 数据行
     * @return {*}
     */
    handleSelectionChange(selection) {
      this.selectFeatures = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /**
     * @description:  初始化featurelayer
     * @param {*}
     * @return {*}
     */
    initFeatureLayer() {
      let _self = this;
      _self.featureLayer = new FeatureLayer({
        title: this.featureLayerTitle,
        url: this.featureLayerUrl,
        outFields: ["objectid"],
        definitionExpression: _self.dataScope,
      });
      _self.featureLayer.effect = null;
      _self.featureLayer.featureEffect = {
        filter: {
          where: "hczt=0",
        },
        includedEffect: "opacity(1)",
        excludedEffect: "opacity(0.5)",
      };
      _self.mapview.map.addMany([
        createLayer("xzqhlayer"),
        createLayer("citykfbjlayer"),
        _self.featureLayer,
      ]);
      _self.featureLayer
        .when(() => {
          return _self.featureLayer.queryExtent();
        })
        .then((response) => {
          _self.mapview.goTo(response.extent.expand(0.7));
          // 初始范围
          _self.homeViewpoint = response.extent.expand(0.7); //_self.mapview.viewpoint.clone();
        });

      _self.mapview.whenLayerView(_self.featureLayer).then((layerView) => {
        console.log(layerView);
        _self.layerView = layerView;
        this.getList();
      });
      _self.mapview.on("click", function (event) {
        // Search for graphics at the clicked location. View events can be used
        // as screen locations as they expose an x,y coordinate that conforms
        // to the ScreenPoint definition.
        _self.mapview.hitTest(event).then(async function (response) {
          if (response.results.length) {
            let graphic = response.results.filter(function (result) {
              // check if the graphic belongs to the layer of interest
              return result.graphic.layer === _self.featureLayer;
            })[0].graphic;
            _self.handleLocate(graphic, true);
            let queryParams = {
              outFields: ["*"],
              where: `objectid=${graphic.attributes["objectid"]}`,
              returnGeometry: true,
            };
            const featureSet = await _self.featureLayer.queryFeatures(
              queryParams
            );
            const feature = featureSet.features[0];

            let paramObj = {
              feature: feature,
              featureLayer: _self.featureLayer,
              selectedGraphic: _self.selectedGraphic,
              layerView: _self.layerView,
            };
            _self.toggleComponent("detailPanel", paramObj);
          }
        });
      });
    },
    /**
     * @description: 根据查询参数构建where查询条件
     * @return {*}
     */
    getWhereClause() {
      let _self = this;
      //   queryParams
      let whereClause = "1=1";
      if (_self.queryParams.name)
        whereClause += " and name like '%" + _self.queryParams.name + "%'";
      if (_self.queryParams.hczt)
        whereClause += ` and hczt ='${_self.queryParams.hczt}'`;
      //根据数据权限过滤数据
      if (_self.dataScope) whereClause += ` and ${_self.dataScope}`;
      return whereClause;
    },
    // 重置查询条件
    resetQueryParams() {
      let _self = this;
      _self.selectTypes = [];
      _self.selectXzqhs = [];
      _self.queryParams.name = null;
      _self.queryParams.category_type = null;
      _self.queryParams.medium_type = null;
      _self.queryParams.hczt = null;
      _self.selectedGraphic = null;
      _self.whereClause = null;
      _self.queryExtent = null;
      _self.layerView.filter = null;
    },
    /** 查询数据列表 */
    getList() {
      let _self = this;
      _self.loading = true;
      _self.whereClause = _self.getWhereClause();
      // 先构建用于查询数据总条数的查询参数对象
      let queryParams = {
        // 空间查询方式，相交查询
        spatialRelationship: "intersects",
        // 空间查询范围
        geometry: _self.queryExtent == null ? null : _self.queryExtent.geometry, // 草绘要素几何
        // 输出字段
        outFields: ["objectid"],
        returnGeometry: true,
        where: _self.whereClause,
      };
      // 查询数据总条数用于渲染分页组件
      _self.featureLayer
        .queryFeatureCount(queryParams)
        .then(function (numResults) {
          _self.total = numResults;
        });
      // 高亮显示选定空间范围内的数据
      if (_self.queryExtent != null) {
        // 添加returnGeometry: true参数，让查询返回结果有geometry，这样九能高亮显示
        queryParams = { returnGeometry: true, ...queryParams };
        _self.featureLayer.queryFeatures(queryParams).then((featureSet) => {
          _self.mapview.goTo(_self.queryExtent);
          if (_self.highlight) {
            _self.highlight.remove();
          }
          // 高亮显示当前页要素
          _self.highlight = _self.layerView.highlight(featureSet.features);
        });
      }
      // 分页查询并在表格展示数据
      queryParams = {
        spatialRelationship: "intersects",
        geometry: _self.queryExtent == null ? null : _self.queryExtent.geometry, // 草绘要素几何
        start: (_self.queryParams.pageNum - 1) * _self.queryParams.pageSize,
        num: _self.queryParams.pageSize,
        outFields: _self.outFields, //["*"],
        returnGeometry: false,
        orderByFields: ["objectid"],
        where: _self.whereClause,
      };

      _self.featureLayer.queryFeatures(queryParams).then((featureSet) => {
        _self.features = featureSet.features;
        // if (_self.highlight) {
        //   _self.highlight.remove();
        // }
        // 高亮显示当前页要素
        // _self.highlight = _self.layerView.highlight(featureSet.features);

        _self.loading = false;
      });
    },
    /** 定位按钮操作 */
    async handleLocate(row, isHighlight = true) {
      let _self = this;
      let queryParams = {
        outFields: ["*"],
        where: `objectid=${row.attributes["objectid"]}`,
        returnGeometry: true,
      };
      const featureSet = await _self.featureLayer.queryFeatures(queryParams);
      const feature = featureSet.features[0];
      if (isHighlight) {
        // 移除前一个高亮图形
        _self.removeHighlight("roadld_highlight");
        // 高亮显示当前页要素;
        _self.setHighlight({
          key: "roadld_highlight",
          value: _self.layerView.highlight(featureSet.features),
        });
      }
      if (feature.geometry == null) {
        _self.$message.error("暂无空间信息");
        return;
      }
      _self.mapview.goTo(feature.geometry.extent.expand(1)).catch((error) => {
        if (error.name != "AbortError") {
          console.error(error);
        }
      });
    },
    // 行政区划选择
    handleChangeXzqh(value) {
      let _self = this;
      // 清空上一次的选择内容
      _self.queryParams.suosjd = null;
      _self.queryParams.suossq = null;
      let xzqhName;
      if (value.length == 1) {
        _self.queryParams.suosjd = value[0];
        xzqhName = value[0];
      } else {
        _self.queryParams.suossq = value[1];
        xzqhName = value[1];
      }
      // 从store中获取行政区划图层
      const xzqhFeatureLayer = _self.$store.getters.xzqhFeatureLayer;
      xzqhFeatureLayer
        .queryFeatures({
          where: `name='${xzqhName}'`,
          returnGeometry: true,
        })
        .then((results) => {
          // 定位高亮显示
          if (results.features.length > 0) {
            _self.mapview
              .goTo(results.features[0].geometry.extent.expand(1))
              .catch((error) => {
                if (error.name != "AbortError") {
                  console.error(error);
                }
              });
            if (_self.selectedGraphic != null)
              _self.mapview.graphics.remove(_self.selectedGraphic);
            _self.selectedGraphic = new Graphic({
              geometry: results.features[0].geometry,
              symbol: xzqhFeatureLayer.symbol,
            });
            _self.mapview.graphics.add(_self.selectedGraphic);
          }
        });
      _self.handleQuery();
    },
    // 核查状态选择事件
    handleChangeHczt(value) {
      // 过滤地图显示内容
      this.layerView.filter = { where: `hczt =${value}` };
      this.handleQuery();
    },
    // 绘制查询范围
    drawExtent(drawType) {
      let _self = this;
      _self.clearGraphics();
      // 添加草绘微件
      const graphicsLayerSketch = new GraphicsLayer();
      const sketchViewModel = new SketchViewModel({
        id: drawType,
        view: _self.mapview,
        layer: graphicsLayerSketch,
        polygonSymbol: _self.selectExtentSymbol,
      });
      sketchViewModel.on("create", (event) => {
        if (event.state === "complete") {
          console.log("Sketch complete");
          // 地图上添加绘制范围
          _self.mapview.graphics.add(event.graphic);
          _self.queryExtent = event.graphic;
        }
      });
      sketchViewModel.create(drawType);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.resetQueryParams();
      this.handleQuery();
      this.clearGraphics();
      this.mapview.goTo(this.homeViewpoint);
      this.cleanHighlight();
    },
    // 清除临时图形
    clearGraphics() {
      let _self = this;
      _self.mapview.popup.close();
      _self.mapview.graphics.removeAll();
      if (_self.highlight) {
        _self.highlight.remove();
      }
    },
    /** 详细按钮操作 */
    async handleView(row) {
      let _self = this;
      console.log(row);
      this.handleLocate(row, true);
      let queryParams = {
        outFields: ["*"],
        where: `objectid=${row.attributes["objectid"]}`,
        returnGeometry: true,
      };
      const featureSet = await _self.featureLayer.queryFeatures(queryParams);
      const feature = featureSet.features[0];
      let paramObj = {
        feature: feature,
        featureLayer: this.featureLayer,
        selectedGraphic: this.selectedGraphic,
        layerView: this.layerView,
      };
      this.toggleComponent("detailPanel", paramObj);
    },
  },
};
</script>

<style>
.title-row {
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  color: #11a983;
  margin-bottom: 1vh;
}
</style>
